/*
 * Copyright 2019 Web3 Labs Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
package org.web3j.web3jevmexample;

import org.web3j.crypto.Credentials;
import org.web3j.crypto.Hash;
import org.web3j.java.APIConsumer;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.admin.Admin;
import org.web3j.protocol.core.methods.response.EthAccounts;
import org.web3j.protocol.core.methods.response.EthBlock;
import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
import org.web3j.protocol.core.methods.response.Log;
import org.web3j.protocol.core.methods.response.Transaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.gas.DefaultGasProvider;
import org.web3j.utils.Numeric;

import java.io.IOException;
import java.math.BigInteger;
import java.util.List;

public class SearchBalance {

    public static void main(String... args) throws Exception {
        // 账户地址和私钥
        String fromAddress = "0x627306090abaB3A6e1400e9345bC60c78a8BEf57"; // 创世文件_内置账户地址2
        String privateKey = "c87509a1c067bbde78beb793e6fa76530b6382a4c0241e5e4a9ec0a0f44dc0d3";// 内置账户_私钥
        Credentials originalCredentials = Credentials.create(privateKey);
        //System.out.println("Original Credentials Address : " + originalCredentials.getAddress());

        String senderAddress = "f17f52151EbEF6C7334FAD080c5704D77216b732"; // 发送者_创世文件_内置账户地址3
        String senderPrivateKey = "ae6ae8e5ccbfb04590405997ee2d52d2b330726137b875053c36d94e974d162f";// 发送者_内置账户_私钥
        Credentials sengderOriginalCredentials = Credentials.create(senderPrivateKey);

        //String linkTokenAddress = "0x8cdaf0cd259887258bc13a92c0a6da92698644c0";     // LINK 合约地址
        //String linkTokenEIP55 = "0x8CdaF0CD259887258Bc13a92C0a6dA92698644C0";     // LINK 合约 EIP55 格式地址
        String linkTokenAddress = "0xf204a4ef082f5c04bb89f7d5e6568b796096735a";     // LINK 合约地址
        String linkTokenEIP55 = "0xf204a4Ef082f5c04bB89F7D5E6568B796096735a";     // LINK 合约 EIP55 格式地址

        String operatorAddress = "0xf12b5dd4ead5f743c6baa640b0216200e89b60da";      // Operator 合约地址
        String operatorEIP55 = "0xF12b5dd4EAD5F743C6BaA640B0216200e89B60Da";      // Operator 合约 EIP55 格式地址


        //String apiConsumerAddress = "0x9fbda871d559710256a2502a2517b794b482db40";   // APIConsumer合约地址( 0 fee )
        //String apiConsumerAddress = "0xde5491f774f0cb009abcea7326342e105dbb1b2e";   // APIConsumer合约地址 ( 100 fee )
        //String apiConsumerEIP55 = "0xdE5491f774F0Cb009ABcEA7326342E105dbb1B2E";   // APIConsumer合约地址 EIP55 格式地址
        String apiConsumerAddress = "0x8cdaf0cd259887258bc13a92c0a6da92698644c0";

        String atestnetConsumer = "0x8273e4b8ed6c78e252a9fca5563adfcc75c91b2a";     // ATestnetConsumer合约地址
        String evmChainAddress = "0x71965FB3ceAc089Fab7CC69a99C85E2397929523";      // EVM Chain Accounts (chainlink在私有链上的账户地址)
        String jobid = "8d8c66be716c4bcf9a59c5d8e70123db";

        //Web3j web3j = Web3j.build(new HttpService("http://localhost:8545"));
        Web3j web3j = Web3j.build(new HttpService("http://192.168.1.162:8545"));
        Admin admin = Admin.build(new HttpService("http://192.168.1.162:8545"));

        try {
            // 列出所有账户
            EthAccounts accounts = admin.ethAccounts().send();
            System.out.println("Accounts: " + accounts.getAccounts());

            // 创建新账户
            String newAccount = admin.personalNewAccount("123456").send().getAccountId();
            System.out.println("New account created: " + newAccount);

            // 重新列出所有账户以确认
            accounts = admin.ethAccounts().send();
            System.out.println("Updated Accounts: " + accounts.getAccounts());

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }




        //// 输出账户列表
        //EthAccounts ethAccounts = web3j.ethAccounts().send();
        //System.out.println("Number of accounts: " + ethAccounts.getAccounts().size());

        //EthGetBalance fromAddrBalance = web3j.ethGetBalance(fromAddress, DefaultBlockParameterName.LATEST).send();
        //System.out.println("firstSearch fromAddrBalance : " + fromAddrBalance.getBalance());

        //// 查询总供应量
        //LinkToken linkToken = LinkToken.load(linkTokenAddress, web3j, originalCredentials, new DefaultGasProvider());
        //BigInteger totalSupply = linkToken.totalSupply().send();
        //System.out.println("totalSupply : " + totalSupply);

/**
        // 查询链上LINK 合约地址
        LinkToken linkToken = LinkToken.load(linkTokenAddress, web3j, originalCredentials, new DefaultGasProvider());
        String linkAddress = linkToken.getContractAddress();
        System.out.println("linkAddress 合约地址 : " + linkAddress);

        // 根据合约地址 查询 合约的代码 (查询合约是否存在)
        EthGetCode ethGetCode = web3j.ethGetCode(linkTokenAddress, DefaultBlockParameterName.LATEST).send();
        String code = ethGetCode.getCode();
        if (code != null && !code.equals("0x")) {
            System.out.println("合约已部署在地址: " + linkAddress);
        } else {
            System.out.println("合约未部署在地址: " + linkAddress);
        }
*/


/**
        LinkToken linkToken = LinkToken.load(linkTokenEIP55, web3j, originalCredentials, new DefaultGasProvider());
        //查询link余额
        BigInteger fromAddressBalance = linkToken.balanceOf(fromAddress).send();
        System.out.println("fromAddressBalance Link Balance: " +fromAddressBalance );
        BigInteger apiConsumerAddressBalance = linkToken.balanceOf(apiConsumerAddress).send();
        System.out.println("apiConsumerAddressBalance Link Balance: " + apiConsumerAddressBalance );

        BigInteger amount = BigInteger.valueOf(1000).multiply(BigInteger.TEN.pow(18)); // 授权的数量

        // 调用 approve 授权方法
        TransactionReceipt txReceipt =linkToken.approve(fromAddress, amount).send();
        System.out.println("授权成功，已给予 " + fromAddress + " 使用 " + amount+" 权限.");
        TransactionReceipt txReceipt2 =linkToken.approve(apiConsumerAddress, amount).send();
        System.out.println("授权成功，已给予 " + apiConsumerAddress + " 使用 " + amount+" 权限.");
        TransactionReceipt txReceipt3 =linkToken.approve(operatorEIP55, amount).send();
        System.out.println("授权成功，已给予 " + operatorEIP55 + " 使用 " + amount+" 权限.");
*/


/**
        // 查询 apiConsumer  link余额
        LinkToken linkToken = LinkToken.load(linkTokenAddress, web3j, originalCredentials, new DefaultGasProvider());
        BigInteger apiConsumerBalance = linkToken.balanceOf(apiConsumerAddress).send();
        System.out.println("apiConsumerAddress Link Balance: " + apiConsumerBalance );
        //BigInteger linkAddressBalance = linkToken.balanceOf(linkTokenAddress).send();
        //System.out.println("linkAddress Link Balance: " + linkAddressBalance );
*/



 /**
        //查询交易记录
        EthGetTransactionReceipt receipt = web3j.ethGetTransactionReceipt(transactionHash).send();
        Optional<TransactionReceipt> transactionReceipt = receipt.getTransactionReceipt();

        if (transactionReceipt.isPresent()) {
            List<Log> logs = transactionReceipt.get().getLogs();
            for (Log log : logs) {
                System.out.println("Log: " + log.getData());
            }
        }
*/


 /**
        // 根据交易 hash 查询交易
        String transactionHash  = "0x74373e23679bd4fb03e95fbcc9c12b290b09bade8673047b7ebdb77f80c9e736";
        // 查询交易收据
        EthGetTransactionReceipt receiptResponse = web3j.ethGetTransactionReceipt(transactionHash).send();
        TransactionReceipt receipt = receiptResponse.getTransactionReceipt().orElse(null);

        if (receipt != null) {
            // 获取合约地址
            String contractAddress = receipt.getContractAddress();
            if (contractAddress != null) {
                System.out.println("Contract Address: " + contractAddress);
            } else {
                System.out.println("This transaction did not deploy a contract.");
            }
        } else {
            System.out.println("Transaction receipt not found.");
        }
*/


/**
        // 根据区块哈希查询区块交易信息
        String blockHash = "0x74373e23679bd4fb03e95fbcc9c12b290b09bade8673047b7ebdb77f80c9e736";
        try {
            // 查询区块，获取详细的交易信息
            EthBlock ethBlock = web3j.ethGetBlockByHash(blockHash, true).send();
            if (ethBlock.getBlock() != null) {
                List<EthBlock.TransactionResult> transactions = ethBlock.getBlock().getTransactions();

                for (EthBlock.TransactionResult txResult : transactions) {
                    // 获取交易对象
                    Transaction transaction = (Transaction) txResult.get();
                    // 获取交易哈希
                    String txHash = transaction.getHash();

                    // 查询每笔交易的收据
                    EthGetTransactionReceipt receiptResponse = web3j.ethGetTransactionReceipt(txHash).send();
                    TransactionReceipt receipt = receiptResponse.getTransactionReceipt().orElse(null);

                    if (receipt != null) {
                        // 获取合约地址
                        String contractAddress = receipt.getContractAddress();
                        if (contractAddress != null) {
                            System.out.println("Contract Address: " + contractAddress); // 0x8cdaf0cd259887258bc13a92c0a6da92698644c0
                        }
                    }
                }
            } else {
                System.out.println("Block not found.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
*/



/**
        APIConsumer apiConsumer =APIConsumer.load(apiConsumerAddress,web3j,originalCredentials,new DefaultGasProvider());
        TransactionReceipt apiConsumerReceipt = apiConsumer.requestVolumeData().send();
        List<Log> logs = apiConsumerReceipt.getLogs();
        for (Log log : logs) {
            System.out.println("Log: " + log.getData());
        }
        System.out.println("调用APIConsumer requestVolumeData 交易成功");
        BigInteger apiConsumerVolume = apiConsumer.volume().send();
        System.out.println("APIConsumer volume: " + apiConsumerVolume);
*/


        web3j.shutdown();

    }



    // 转成EIP55格式的地址
    public static String toChecksumAddress(String address) {
        if ((address != null && !address.trim().isEmpty()) && address.startsWith("0x")) {
            String addressWithoutPrefix = address.substring(2);
            String hashedAddress = Numeric.toHexStringNoPrefix(Hash.sha3(addressWithoutPrefix.toLowerCase().getBytes()));

            StringBuilder checksumAddress = new StringBuilder("0x");
            for (int i = 0; i < addressWithoutPrefix.length(); i++) {
                // 根据哈希值的每个字符决定当前字符是大写还是小写
                if (Integer.parseInt(String.valueOf(hashedAddress.charAt(i)), 16) > 7) {
                    checksumAddress.append(Character.toUpperCase(addressWithoutPrefix.charAt(i)));
                } else {
                    checksumAddress.append(addressWithoutPrefix.charAt(i));
                }
            }
            return checksumAddress.toString();
        }
        throw new IllegalArgumentException("Invalid address format");
    }

}

